from flask_restplus import Resource, Namespace, fields, marshal, reqparse, Model
from common.responses import ok
from common import constant
from common.response_model import base_model, pagination_model

from app.product.unit.controller import unit_model
from app.file.controller import file_model
from app.file.model import FileRelation, File
from common.request_parser import get_parser as base_get_parser
from common.decorators import catch_error, arguments_parser
from app.user.decorators import token_required
from app.product.sku import dao
from app.product.sku.model import Sku
from app.product.unit.model import Unit
from app.product.sku.model import SkuToUnit

api = Namespace('sku')


def get_img_files_from_sku(sku):
    obj_to_files = FileRelation.query.filter_by_company_id(
        belong_id=sku.id,
        belong_type=constant.FileBelongType.SKU).all()
    files = []
    for ele in obj_to_files:
        file = File.query.filter_by(id=ele.file_id).first()
        # 过滤图片
        files.append(file)
    return files


from app.product.spu.model import Spu


def get_sku_name(sku):
    spu = Spu.query.filter_by(id=sku.spu_id).first()
    # 如果未开启多规格
    if not spu.is_multiple_spec:
        return spu.name
    else:  # 多规格
        attrs = []
        for key, value in sku.spec_attr_ele.items():
            attrs.append(value)
        return spu.name + ' ' + ' '.join(attrs)


def get_spu_spec_string(sku):
    spu = Spu.query.filter_by(id=sku.spu_id).first()
    if spu.is_multiple_spec:
        return spu.spec_string
    else:
        return ''

# ---------- model ----------
sku_model = base_model.inherit('sku_model', {
    "sku_sn": fields.String(description='商品货号'),
    'warning_number_low': fields.Integer(description='库存预警下限'),
    'warning_number_high': fields.Integer(description='库存预警上限'),
    'barcode': fields.String(description='条形码'),
    'spec_attr_ele': fields.Raw(description='规格属性'),
    'images': fields.List(fields.Nested(file_model), attribute=lambda spu: get_img_files_from_sku(spu)),
    'is_in_db': fields.Boolean(description='是否已经入库', attribute=lambda sku: True),
    # 名称
    'name_and_spec_attr_ele': fields.String(attribute=lambda sku: get_sku_name(sku), description='名称'),
    'spec_string': fields.String(attribute=lambda sku: get_spu_spec_string(sku), description='型号规格'),
})

simple_sku_model = Model('sku_model', {
    'id': fields.Integer(description='编号'),
    'name': fields.String(description='名称'),
    "sku_sn": fields.String(description='商品货号'),
    'spec_attr_ele': fields.Raw(description='规格属性'),
})

sku_unit_price_model = Model('sku_unit_model', {
    'id': fields.Integer(description='编号'),
    "sku": fields.Nested(sku_model),
    "unit": fields.Nested(unit_model),
    "purchase_price": fields.Float(description='采购价'),
    "sale_price": fields.Float(description='销售价'),
})

sku_unit_price_model_with_storage = Model('sku_unit_model', {
    'id': fields.Integer(description='编号'),
    "sku": fields.Nested(sku_model),
    "unit": fields.Nested(unit_model),
    "purchase_price": fields.Float(description='采购价'),
    "sale_price": fields.Float(description='销售价'),

    # # 当前库存
    # "current_num": fields.Integer(description='当前库存'),
})

sku_paginate_model = pagination_model.inherit('sku_paginate_model', {
    "items": fields.Nested(sku_model)
})

get_parser = base_get_parser.copy()
get_parser.add_argument('category_id', type=int, help='按类别筛选，会筛选所有子类')


# get_parser.add_argument('warehouse_id', type=int, required=True)

class SkuUnitPricesResource(Resource):
    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取sku单位价格"""
        args = get_parser.parse_args()
        pagination = dao.get_sku_unit_prices(**args)
        new_items = []
        for ele in pagination['items']:
            sku_to_unit = SkuToUnit.query.filter_by(id=ele['id']).first()
            # print('sku_to_unit', sku_to_unit)
            # print('sku_to_unit.sku.spu_id', sku_to_unit.sku.spu_id)
            # print('sku_json', marshal(sku_to_unit.sku, sku_model))
            sku_to_unit_json = marshal(sku_to_unit, sku_unit_price_model_with_storage)
            # print('sku_to_unit_json', sku_to_unit_json)
            new_items.append(sku_to_unit_json)
        pagination['items'] = new_items
        return ok(data=pagination,
                  message='get success')


# --------- route ----------
# api.add_resource(SkusResource, '/skus')
# api.add_resource(SkuResource, '/skus/<int:obj_id>')
#
# api.add_resource(SpuBatchSkuResource, '/spu_batch_sku')
# api.add_resource(SpuBatchSkuToUnitResource, '/spu_batch_sku_to_unit')

# sku + unit
api.add_resource(SkuUnitPricesResource, '/sku_unit_prices')

# 注册文档
api.models[sku_model.name] = sku_model
